class PopupController {
  constructor() {
    this.startTime = null;
    this.timer = null;
    this.isCollecting = false;

    this.controlBtn = document.getElementById('controlBtn');
    this.counter = document.getElementById('counter');
    this.memUsage = document.getElementById('memUsage');
    this.duration = document.getElementById('duration');
    this.progressBar = document.getElementById('progressBar');

    this.initEventListeners();
    this.setupRuntimeListener();
  }

  initEventListeners() {
    this.controlBtn.addEventListener('click', () => {
      if (this.isCollecting) {
        this.stopCollection();
      } else {
        this.startCollection();
      }
    });
  }

  setupRuntimeListener() {
    chrome.runtime.onMessage.addListener((message) => {
      if (message.type === 'newLinks') {
        this.updateCounter(message.count);
      }
      if (message.type === 'memoryUpdate') {
        this.updateMemoryDisplay(message.usage);
      }
    });
  }

  startCollection() {
    this.isCollecting = true;
    this.startTime = new Date();
    this.controlBtn.textContent = '停止采集';
    this.controlBtn.classList.add('warning');

    chrome.runtime.sendMessage({ action: 'startCollection' });
    this.startTimer();
  }

  stopCollection() {
    this.isCollecting = false;
    this.controlBtn.textContent = '开始采集';
    this.controlBtn.classList.remove('warning');
    clearInterval(this.timer);

    chrome.runtime.sendMessage({ action: 'stopCollection' });
  }

  startTimer() {
    this.timer = setInterval(() => {
      const seconds = Math.floor((new Date() - this.startTime) / 1000);
      this.duration.textContent = `${String(Math.floor(seconds / 60)).padStart(
        2,
        '0'
      )}:${String(seconds % 60).padStart(2, '0')}`;
    }, 1000);
  }

  updateCounter(count) {
    this.counter.textContent = count;
    this.progressBar.value = Math.min((count / 1000) * 100, 100);
  }

  updateMemoryDisplay(usage) {
    this.memUsage.textContent = `${(usage / 1024 / 1024).toFixed(1)}MB`;
  }
}

// 初始化弹窗控制器
new PopupController();
